#include "route.hpp"
#include "db_manager.hpp"
#include <sstream>
#include <iomanip>

std::vector<Route> Route::getAll() {
    std::vector<Route> routes;
    auto* mysql = DBManager::getInstance().getConnection();
    
    const char* query = "SELECT id, modid, cmdid, serverip, serverport FROM RouteData";
    if (mysql_query(mysql, query)) {
        return routes;
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        return routes;
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        Route route;
        route.id = std::stoi(row[0]);
        route.modid = std::stoi(row[1]);
        route.cmdid = std::stoi(row[2]);
        route.serverip = std::stoul(row[3]);
        route.serverport = std::stoi(row[4]);
        routes.push_back(route);
    }
    
    mysql_free_result(result);
    return routes;
}

Route Route::getById(int id) {
    Route route;
    auto* mysql = DBManager::getInstance().getConnection();
    
    std::stringstream ss;
    ss << "SELECT id, modid, cmdid, serverip, serverport FROM RouteData WHERE id = " << id;
    
    if (mysql_query(mysql, ss.str().c_str())) {
        return route;
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        return route;
    }
    
    MYSQL_ROW row = mysql_fetch_row(result);
    if (row) {
        route.id = std::stoi(row[0]);
        route.modid = std::stoi(row[1]);
        route.cmdid = std::stoi(row[2]);
        route.serverip = std::stoul(row[3]);
        route.serverport = std::stoi(row[4]);
    }
    
    mysql_free_result(result);
    return route;
}

bool Route::add(int modid, int cmdid, uint32_t serverip, int serverport) {
    auto* mysql = DBManager::getInstance().getConnection();
    
    std::stringstream ss;
    ss << "INSERT INTO RouteData (modid, cmdid, serverip, serverport) VALUES ("
       << modid << ", " << cmdid << ", " << serverip << ", " << serverport << ")";
    
    return mysql_query(mysql, ss.str().c_str()) == 0;
}

bool Route::update(int id, int modid, int cmdid, uint32_t serverip, int serverport) {
    auto* mysql = DBManager::getInstance().getConnection();
    
    std::stringstream ss;
    ss << "UPDATE RouteData SET modid = " << modid 
       << ", cmdid = " << cmdid 
       << ", serverip = " << serverip 
       << ", serverport = " << serverport 
       << " WHERE id = " << id;
    
    return mysql_query(mysql, ss.str().c_str()) == 0;
}

bool Route::remove(int id) {
    auto* mysql = DBManager::getInstance().getConnection();
    
    std::stringstream ss;
    ss << "DELETE FROM RouteData WHERE id = " << id;
    
    return mysql_query(mysql, ss.str().c_str()) == 0;
} 